package thread;

import java.util.concurrent.TimeUnit;

class MyData {
    volatile int num = 0;

    public void addTo10() {
        this.num = 10;
    }
}

/*
验证volatile的可见性
如果不加volatile关键字num被线程A修改之后，main线程是不可见的。
 volatile保证可见性，当线程修改值之后会及时通知其他线程，主物理内存的值已经被修改
 */
public class VolatileDemo {
    public static void main(String[] args) {
        MyData myData = new MyData();
        //实现Runnable接口的lambda表达式
        //线程A
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "com in");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //num赋值为10
            myData.addTo10();
            System.out.println("after 3 second this num is:" + myData.num);
        }, "thread A").start();

        while (myData.num == 0) {
            //if num=0 then main loop in here
        }
        System.out.println(Thread.currentThread().getName() + " marry with me");
    }
}
